package com.feng.study.service.localhost;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.study.dao.UserDao;
import com.feng.study.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

@Service
public class UserService extends ServiceImpl<UserDao, UserEntity> {

    @Autowired
    private  TransactionTemplate transactionTemplate;

    public void saveList(){
        UserEntity userEntity = new UserEntity();
        userEntity.setAge(112);
        UserEntity userEntity2 = new UserEntity();
        userEntity2.setAge(113);
        List<UserEntity> userEntityList = Arrays.asList(userEntity,userEntity2);
        this.saveBatch(userEntityList);
        System.out.println();
    }

    public List<UserEntity> listUser(String name){
        return this.baseMapper.listUser(name);
    }

//    @Transactional(rollbackFor = Exception.class)
    public void testTransactionTemplate() {
        UserEntity userEntity1 = new UserEntity().setName("aaaa").setId(1L).setAge(22).setAddress("abc");
        UserEntity userEntity2 = new UserEntity().setName("aaaa1").setId(5L).setAge(22).setAddress("abc");
        System.out.println("事务开始---");
        transactionTemplate.execute(execute->{
            try{
                this.updateById(userEntity1);
                this.save(userEntity2);
            }catch (Exception e){
                execute.setRollbackOnly();
                log.error("事务执行失败----回滚数据");
            }
            return "ddd";
        });

        System.out.println("结束");
    }
}
